# _*_ coding: utf-8 _*_
import urllib.parse
import requests
from logger import logger


class WeiBoLogin(object):
    def __init__(self):
        self.session = requests.Session()
        self.session.headers.update(
            {"User-Agent": "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0"})
        self.session.get("http://weibo.com/login.php")

    def login(self, username, password):
        data = {
            'username': username,
            'password': password,
            'savestate': 1,
            'r': 'http: // m.weibo.cn',
            'ec': 0,
            'pagerefer': 'https://m.weibo.cn/p/102803_ctg1_8999_-_ctg1_8999_home',
            'entry': 'mweibo',
            'wentry': '',
            'loginfrom': '',
            'client_id': '',
            'code': '',
            'qq': '',
            'mainpageflag': 1,
            'hff': '',
            'hfp': ''
        }
        headers = {
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1',
            'Referer': 'https://passport.weibo.cn/signin/login?entry=mweibo&r=http%3A%2F%2Fm.weibo.cn'
        }
        url = 'https://passport.weibo.cn/sso/login'

        resp = self.session.post(url, data, headers=headers)
        logger.info(resp.json())
        if resp.status_code == 200 and resp.json()['retcode'] == 20000000:
            url1 = resp.json()['data']['loginresulturl']
            uid = resp.json()['data']['uid']
            resp = self.session.get(url1)
            decode1 = urllib.parse.unquote(url1)
            url2 = decode1[decode1.find('cdurl') + 6:]
            resp = self.session.get(url2)
            decode2 = urllib.parse.unquote(url2)
            url3 = decode2[decode2.find('cdurl') + 6:]
            resp = self.session.get(url3)
            resp = self.session.get('https://weibo.cn')
            return self.session
        else:
            logger.info(u'登录失败')
